//
//  LTAppDelegate.m
//  LocalTravel
//
//  Created by zheng ji on 14-2-25.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "LTAppDelegate.h"
#import "constants.h"
#import "LTLeftViewController.h"
#import "LTMapViewController.h"
#import "MobClick.h"
#import "CommonConfigUtil.h"
@interface LTAppDelegate()
{
    NSArray* _provinceArrayData;
    NSDictionary *_pushPayload;
}
@end
@implementation LTAppDelegate

-(void)initApp{
      myDefaults=[NSUserDefaults standardUserDefaults];
    [MobClick startWithAppkey:[CommonConfigUtil getUmengAppKey] reportPolicy:REALTIME channelId:[CommonConfigUtil getChannelId]];
    
    //[self createAdvList];
    
    //应用启动时先清理掉本地暂存的图片
    
       [NSThread detachNewThreadSelector:@selector(clearCacheImage) toTarget:self withObject:nil];
    
       [NSThread detachNewThreadSelector:@selector(addMobileUser:) toTarget:self withObject:@"N"];
    
}
- (void)addMobileUser:(NSString *)isSleep{
    
    
    if(nil!=isSleep && [@"Y" isEqualToString:isSleep]){
        [NSThread sleepForTimeInterval:5];
    }
    
    if(![CommonConfigUtil checkNetworkReachable]){
		return ;
	}
    
    NSString *openUDID=[[[UIDevice currentDevice] identifierForVendor] UUIDString];
    if(nil==openUDID||[@"" isEqualToString:openUDID]){
        return;
    }
    
    NSString *deviceInfo= [CommonConfigUtil getDeviceInfo];
    
    NSMutableString *url = [[NSMutableString alloc] initWithFormat:@"%@/saveMobileuser/?type=%@&uuid=%@&appversion=%@",[CommonConfigUtil getInfServiceUrl],[CommonConfigUtil getVersionType],openUDID,[CommonConfigUtil getMobileClientApp]];
    
    
    if(nil!=[myDefaults objectForKey:@"userId"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userId"]]){
        [url appendFormat:@"&userid=%@", [myDefaults objectForKey:@"userId"]];
    }
    
    if(nil!=[myDefaults objectForKey:@"userNickname"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userNickname"]]){
        [url appendFormat:@"&username=%@", [[myDefaults objectForKey:@"userNickname"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=[myDefaults objectForKey:@"deviceToken"]&&![@"" isEqualToString:[myDefaults objectForKey:@"deviceToken"]]){
        [url appendFormat:@"&token=%@",[[myDefaults objectForKey:@"deviceToken"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=deviceInfo&&![@"" isEqualToString:deviceInfo]){
        [url appendString:deviceInfo];
    }
    
    // NSLog(@"url:%@",url);
    
    //  NSData *reData=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    // [url release];
    
    NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:
                           NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
    
    NSHTTPURLResponse *urlResponse;
    NSData *reData= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
    
    
    
    if(nil!=reData && [reData length]>0){
        NSError *error=nil;
        NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:reData options:kNilOptions error:&error];
        //NSDictionary *dictionary=[[CJSONDeserializer deserializer] deserializeAsDictionary:reData error:&error];
        
        if(!error){
            NSString  *taobosid=[dictionary objectForKey:@"sid"];//toabosid
            if(nil!=taobosid && ![@"" isEqualToString:taobosid]){
                [myDefaults setObject:taobosid forKey:@"taobosid"];
                [myDefaults synchronize];
            }
            
        }
    }
    
    
    reData=nil;
    
    
}

-(void)clearCacheImage{
    
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    NSString *path=[CommonConfigUtil getImageLocalPath];
    [fileManager removeItemAtPath:path error:nil];
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    
    
    
    NSString *filestorePath=[CommonConfigUtil getFileLocalPath];
    if(![fileManager fileExistsAtPath:filestorePath ]){
        [fileManager createDirectoryAtPath:filestorePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    
}
/**
  处理加载消息
*/
-(void)parseLaunchingOptions:(NSDictionary *)launchOptions
{
    [UIApplication sharedApplication].applicationIconBadgeNumber=0; 
    NSDictionary *payload=[launchOptions  objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if(nil!=payload){
        NSDictionary *aps=[payload objectForKey:@"aps"];
        NSString *alertMessage=[aps objectForKey:@"alert"]; 
        if(nil==alertMessage){
            alertMessage=@"" ;
        }

        NSString *advtype =[payload objectForKey:@"t"];//advtype
        NSString *objectid =[payload objectForKey:@"i"];
        NSString *objectname =[payload objectForKey:@"n"];
        NSString *batchId =[payload objectForKey:@"b"];//批量
        
        if(nil==advtype)advtype=@"";
        if(nil==objectid)objectid=@"";
        if(nil==objectname)objectname=@"";
        if(nil==batchId)batchId=@"";
        
        NSDictionary *params=[NSDictionary dictionaryWithObjectsAndKeys:advtype,@"advtype",@"",@"name",objectid,@"objectId",objectname,@"objectName",alertMessage,@"title",batchId,@"batchid",nil];
    
        
        if([@"10" isEqualToString:advtype] || [advtype intValue]==10){//评分
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" 
                                                           // message:@"亲，喜欢我就给我个评分吧，您的评价真得很重要！" 
                                                             message:alertMessage 
                                                           delegate:self 
                                                  cancelButtonTitle:@"残忍拒绝" 
                                                  otherButtonTitles:@"仁慈给予",nil]; 
            [alert setTag:998];
            [alert show]; 
             
        }
        else  if([@"11" isEqualToString:advtype] || [advtype intValue]==11){//分享
	  /*
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" 
                                                            //message:@"亲，喜欢我就与朋友们分享吧！" 
                                                          message:alertMessage 
                                                           delegate:self 
                                                  cancelButtonTitle:@"残忍拒绝" 
                                                  otherButtonTitles:@"仁慈给予",nil]; 
            [alert setTag:999];
            [alert show]; */
            
        }
        else { 
             [self pushMessageWithParams:params]; 
        }
        
        
         [NSThread detachNewThreadSelector:@selector(savePushMsgLog:) toTarget:self withObject:params];
        
    }
    
}

/**
  接受到远程通知
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo 
{ 
    
    [UIApplication sharedApplication].applicationIconBadgeNumber=0; 
    
    NSDictionary *aps=[userInfo objectForKey:@"aps"];
    NSString *alertMessage=[aps objectForKey:@"alert"]; 
    if(nil!=alertMessage){
        
        NSString *advtype =[userInfo objectForKey:@"t"];//advtype
        NSString *objectid =[userInfo objectForKey:@"i"];
        NSString *objectname =[userInfo objectForKey:@"n"];
        NSString *batchId =[userInfo objectForKey:@"b"];//批量
        
     
        if(nil==advtype)advtype=@"";
        if(nil==objectid)objectid=@"";
        if(nil==objectname)objectname=@"";
         if(nil==batchId)batchId=@"";
        
        
        _pushPayload=[NSDictionary dictionaryWithObjectsAndKeys:advtype,@"advtype",@"",@"name",objectid,@"objectId",objectname,@"objectName",alertMessage,@"title",batchId,@"batchid",nil];
        
         [NSThread detachNewThreadSelector:@selector(savePushMsgLog:) toTarget:self withObject:_pushPayload];
        
        if([@"10" isEqualToString:advtype] || [advtype intValue]==10){//评分
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" 
                                                           // message:@"亲，喜欢我就给我个评分吧，您 的评价真得很重要！"
                                                           message:alertMessage 
                                                           delegate:self 
                                                  cancelButtonTitle:@"残忍拒绝" 
                                                  otherButtonTitles:@"仁慈给予",nil]; 
            [alert setTag:998];
            [alert show]; 
             
        }
        else  if([@"11" isEqualToString:advtype] || [advtype intValue]==11){//分享
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" 
                                                           // message:@"亲，喜欢我就与朋友们分享吧！" 
                                                           message:alertMessage 
                                                           delegate:self 
                                                  cancelButtonTitle:@"残忍拒绝" 
                                                  otherButtonTitles:@"仁慈给予",nil]; 
            [alert setTag:999];
            [alert show]; 
            
        }
        
        else {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" 
                                                        message:alertMessage 
                                                       delegate:self 
                                              cancelButtonTitle:@"忽略" 
                                              otherButtonTitles:@"显示",nil]; 
        [alert setTag:1000];
        [alert show]; 
          
        }
    
         
        
    }    
    
    
    
} 

//save push message log
-(void)savePushMsgLog:(NSDictionary *)params{

    if(![CommonConfigUtil checkNetworkReachable]){
		return ;
	}

    
  
       
       
    NSString *openUDID=[[[UIDevice currentDevice] identifierForVendor] UUIDString];
    
    if(nil==openUDID){
       openUDID=@"";
    }
    
        
    NSMutableString *url = [[NSMutableString alloc] initWithFormat:@"%@/plus/saveDetailLog/?mobiletype=%@&uuid=%@",[CommonConfigUtil getInfServiceUrl],[CommonConfigUtil getVersionType],openUDID]; 
    
 
    if(nil!=[myDefaults objectForKey:@"userId"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userId"]]){
        [url appendFormat:@"&userid=%@", [myDefaults objectForKey:@"userId"]];
    }
    
    if(nil!=[myDefaults objectForKey:@"userNickname"]&&![@"" isEqualToString:[myDefaults objectForKey:@"userNickname"]]){
        [url appendFormat:@"&username=%@", [[myDefaults objectForKey:@"userNickname"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=[myDefaults objectForKey:@"deviceToken"]&&![@"" isEqualToString:[myDefaults objectForKey:@"deviceToken"]]){
        [url appendFormat:@"&token=%@",[[myDefaults objectForKey:@"deviceToken"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    if(nil!=[params objectForKey:@"advtype"]&&![@"" isEqualToString:[params objectForKey:@"advtype"]]){
        [url appendFormat:@"&advtype=%@",[params objectForKey:@"advtype"]];
    }
    
    if(nil!=[params objectForKey:@"objectId"]&&![@"" isEqualToString:[params objectForKey:@"objectId"]]){
        [url appendFormat:@"&objectid=%@",[params objectForKey:@"objectId"]];
    }
    if(nil!=[params objectForKey:@"objectName"]&&![@"" isEqualToString:[params objectForKey:@"objectName"]]){
        [url appendFormat:@"&objectname=%@",[[params objectForKey:@"objectName"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    if(nil!=[params objectForKey:@"title"]&&![@"" isEqualToString:[params objectForKey:@"title"]]){
        [url appendFormat:@"&title=%@",[[params objectForKey:@"title"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    if(nil!=[params objectForKey:@"batchid"]&&![@"" isEqualToString:[params objectForKey:@"batchid"]]){
        [url appendFormat:@"&batchid=%@",[params objectForKey:@"batchid"]];
    }
    
   // NSLog(@"url:%@",url);
    
    //  NSData *reData=[NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
    // [url release];
    
    NSURLRequest *request=[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy: 
                           NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0];
    
    NSHTTPURLResponse *urlResponse;
    NSData *reData= [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
    
    
    
    
    reData=nil;
    
    
 


}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    //评分
    if([alertView tag]==998 && buttonIndex == 1 ) {
     
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[CommonConfigUtil getAppStoreCommentUrl]]];    
    }
    else if([alertView tag]==999 && buttonIndex == 1 ) {
       // [self toShare];
    }
    
    else if([alertView tag]==1000 && buttonIndex == 1 ) {
        
        if( nil!=_pushPayload){
            [self pushMessageWithParams:_pushPayload];    
        }    
    } 
  
    
}

-(void)pushMessageWithParams:(NSDictionary *)params{
    NSString *advid=[params objectForKey:@"advid" ];
    NSString *advtype=[params objectForKey:@"advtype" ];
    //  NSString *name=[params objectForKey:@"name" ];
    NSString *objectId=[params objectForKey:@"objectId" ];
    NSString *objectName=[params objectForKey:@"objectName" ];
    NSString *urlparams=[params objectForKey:@"urlparams" ];
    
    
    
    if(nil!=advid && ![@"" isEqualToString:advid]){
        
        NSDictionary *statParms =[NSDictionary dictionaryWithObjectsAndKeys:advid,@"objectid",@"ad",@"page",nil];
        [NSThread detachNewThreadSelector:@selector(saveMobileStat:) toTarget:self withObject:statParms];
    }
    
    
    NSLog(@"advtype==%@",advtype);
    //类型 0：商品详细页 1：分类列表 2：标签列表 3：店铺详细 4：品牌详细 5：专辑详细 6：场景详细 7：活动详细 8：appstore 9:url
    
    if([@"0" isEqualToString:advtype] || [advtype intValue]==0 ){
        
        
    }
    else  if([@"1" isEqualToString:advtype] || [advtype intValue]==1 ){
        
    }
    else  if([@"2" isEqualToString:advtype] || [advtype intValue]==2 ){
        
        
        
        
    }
    else  if([@"3" isEqualToString:advtype] || [advtype intValue]==3 ){
        
        
    }
    else  if([@"4" isEqualToString:advtype] || [advtype intValue]==4 ){
        
        
    }
    else  if([@"5" isEqualToString:advtype] || [advtype intValue]==5 ){
        
  
    }else  if([@"8" isEqualToString:advtype] || [advtype intValue]==8 ){
        
        
        NSString *appName=@"";
        if(nil!=urlparams && ![@"" isEqualToString:urlparams] ){
            NSArray *paramsArray=[urlparams componentsSeparatedByString:@"appname="];
            if(nil!=paramsArray &&  [paramsArray count]>1 ){
                appName= [paramsArray objectAtIndex:1 ];
            }
            
        }
        
        if(nil==appName)appName=@"";
        
        if(![@"" isEqualToString:appName] && [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:appName]]){
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appName]];
        }
        else{
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:objectName]];
        }
        
    }
    else  if([@"9" isEqualToString:advtype] || [advtype intValue]==9 ){
        
        //start with app:
        if ([objectName hasPrefix:@"app:"]){
            //[self advAppUrlParseWithAppUrl:objectName withUrlparams:urlparams withUINavigationController:navigationController];
        }
        else if(nil!=objectId && ([@"1" isEqualToString:objectId] || [objectId intValue]==1)  ) {
            
            
         
          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:objectName]];
            
        }
        else {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:objectName]];
        }
    }
    

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self initApp];

    [NSThread detachNewThreadSelector:@selector(registerForRemoteNotification) toTarget:self withObject:@"N"]; 

    [self parseLaunchingOptions:launchOptions];
    return YES;
}
-(void)registerForRemoteNotification{
    
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];   
}

- (void)application:(UIApplication *)application 
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
    
    if(nil!=deviceToken) { 
        NSMutableString *strdeviceToken = [[NSMutableString alloc] initWithFormat:@"%@",deviceToken]; 
        if(nil!=strdeviceToken){
       
            
      
            [myDefaults setObject:strdeviceToken forKey:@"deviceToken"];
            [myDefaults synchronize];
            
 
            
            
            strdeviceToken=nil;
            
        }
        
        
    }     
    
    [NSThread detachNewThreadSelector:@selector(addMobileUser:) toTarget:self withObject:@"Y"];
} 

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { 
    // NSLog(@"error:%@",error);
   // [NSThread detachNewThreadSelector:@selector(addMobileUser) toTarget:self withObject:nil]; 
} 

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


-(NSString*) getCityIDByName:(NSString*)cityName{
    if (_provinceArrayData==nil) {
        [self getProvinceData];
    }
    NSString* cityID=@"";
    BOOL isFind=NO;
    for (NSDictionary* dictProvince in _provinceArrayData) {
        if(isFind) break;
        
        NSDictionary* dictCityList=[dictProvince objectForKey:@"cityList"];
        NSObject* obj=[dictCityList objectForKey:@"city"];
        if([obj isKindOfClass:[NSDictionary class]]){
             NSDictionary* d =[dictCityList objectForKey:@"city"];
            NSString* name=[d objectForKey:@"name"];
            if([name isEqualToString:cityName]){
               cityID=[d objectForKey:@"id"];
                isFind=YES;
            }
        }else if([obj isKindOfClass:[NSArray class]]){
            NSArray* array=[dictCityList objectForKey:@"city"];
            
            for (NSDictionary* dictCity in array) {
                NSString* name=[dictCity objectForKey:@"name"];
                if([name isEqualToString:cityName]){
                    cityID=[dictCity objectForKey:@"id"];
                    isFind=YES;
                    break;
                }

            }
            
        }
        
        

    }
    
    return cityID;
}
-(NSArray*) getProvinceData{
 if(_provinceArrayData==nil){
     
    NSString* file=[[NSBundle mainBundle] pathForResource:@"citys" ofType:@"json"];
    NSError* error=nil;
    NSDictionary *dictionary= [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:file] options:kNilOptions error:&error];
    if(!error){
        
        
        NSDictionary *dict=[dictionary objectForKey:@"provincelist"];
        if(dict !=nil && dict.count>0){
            _provinceArrayData=[dict objectForKey:@"province"];
            
        }
        
        
    }
 }
    return _provinceArrayData;

}
@end
